package com.ds.lens.data.service.dao;

import com.ds.lens.data.service.dao.entity.LensRoleResourceRelation;
import com.ds.lens.data.service.dao.sql.provider.LensRoleResourceRelationSqlProvider;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.type.JdbcType;
import org.springframework.stereotype.Repository;

@Repository
public interface LensRoleResourceRelationDao {
    @Delete({
            "delete from lens_role_resource_relation",
            "where id = #{id,jdbcType=BIGINT}"
    })
    int deleteByPrimaryKey(Long id);

    @Insert({
            "insert into lens_role_resource_relation (id, rule_id, ",
            "resource_id)",
            "values (#{id,jdbcType=BIGINT}, #{ruleId,jdbcType=BIGINT}, ",
            "#{resourceId,jdbcType=BIGINT})"
    })
    int insert(LensRoleResourceRelation record);

    @InsertProvider(type = LensRoleResourceRelationSqlProvider.class, method = "insertSelective")
    int insertSelective(LensRoleResourceRelation record);

    @Select({
            "select",
            "id, rule_id, resource_id",
            "from lens_role_resource_relation",
            "where id = #{id,jdbcType=BIGINT}"
    })
    @Results({
            @Result(column = "id", property = "id", jdbcType = JdbcType.BIGINT, id = true),
            @Result(column = "rule_id", property = "ruleId", jdbcType = JdbcType.BIGINT),
            @Result(column = "resource_id", property = "resourceId", jdbcType = JdbcType.BIGINT)
    })
    LensRoleResourceRelation selectByPrimaryKey(Long id);

    @UpdateProvider(type = LensRoleResourceRelationSqlProvider.class, method = "updateByPrimaryKeySelective")
    int updateByPrimaryKeySelective(LensRoleResourceRelation record);

    @Update({
            "update lens_role_resource_relation",
            "set rule_id = #{ruleId,jdbcType=BIGINT},",
            "resource_id = #{resourceId,jdbcType=BIGINT}",
            "where id = #{id,jdbcType=BIGINT}"
    })
    int updateByPrimaryKey(LensRoleResourceRelation record);



    @Select({
            "select count(1) > 0 from lens_resource re ",
            "left join lens_role_resource_relation rr on rr.resource_id = re.id ",
            "left join lens_user_role_relation ur on ur.role_id = rr.rule_id ",
            "WHERE re.url=#{resource} and ur.user_name=#{userName}",
    })
    boolean checkPermission(@Param("userName") String userName,
                            @Param("resource") String resource);
}
